package com.sisgh.jefdv1.core.jdbc.connection;

import com.sisgh.jefdv1.core.jdbc.connection.factory.impl.MySQLConnectionFactory;
import com.sisgh.jefdv1.core.jdbc.connection.factory.ConnectionFactory;
import com.sisgh.jefdv1.core.jdbc.db.Database;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 连接工厂构造器
 */
@Slf4j
public class ConnectionFactoryBuilder {

    private static final Map<String, ConnectionFactory> caches = new HashMap<>();

    /**
     * 用于 mysql
     * @return
     */
    private static ConnectionFactory getMySQLConnectionFactory(){
        String driverName = Database.MYSQL.getDriverName();
        if (caches.containsKey(driverName)){
            /**
             * info 日志
             */
            log.info("mysql 连接工厂从缓存中获取");

            return caches.get(driverName);
        }
        ConnectionFactory mysql = new MySQLConnectionFactory();
        caches.put(driverName, mysql);

        /**
         * info 日志
         */
        log.info(" mysql 连接工厂创建成功，并存入缓存中");

        return mysql;
    }

    /**
     * 获取连接工厂
     * @param db
     * @return
     * @throws SQLException
     */
    public static ConnectionFactory getConnectionFactory(Database db) throws SQLException {
        // 日志
        log.info("初始化 {} 连接工厂", db.getName());


        return switch (db) {
            case MYSQL -> getMySQLConnectionFactory();
            case ORACLE, POSTGRESQL, SQLSERVER -> {
                String unsupported = db.getName() + "connection is not supported";
                log.error(unsupported);
                throw new SQLException(unsupported);
            }
            default -> {
                log.error("不支持的数据库 {}", db.getName());
                throw new SQLException("Unsupported database");
            }
        };
    }
}
